﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Noris.Schedule.Support;
using Noris.Schedule.Support.Parser;
using Noris.Tools.DbManager.Components;
using Noris.Tools.DbManager.Data;
using System.IO;

namespace Noris.Tools.DbManager.Data
{
	internal class Scriptor
	{
		internal static void RunScript(ScriptorData scriptorData)
		{
			DevelopmentData devData = scriptorData.Development;
			int devCnt = devData.Developments.Count;
			int devUka = 0;

			foreach (ConnectProfile profile in scriptorData.Profiles)
			{
				using (Noris.Schedule.Support.Sql.DataConnector connector = Schedule.Support.Sql.DataConnector.Create(Schedule.Support.Sql.DataSourceType.MicrosoftSqlServer, profile.ProfileConnString, System.Data.IsolationLevel.ReadCommitted, true))
				{
					foreach (DevelopmentInfo devOne in devData.Developments)
					{
						devUka++;
						float devInn = devOne.ScriptFiles.Count;

						foreach (FileInfo file in devOne.ScriptFiles)
						{
							List<string> batches = DevelopmentInfo.GetSqlBatchFromScript(file);

							// Progress:
							ScriptProgressData progress = new ScriptProgressData();
							progress.Development = devOne.Development;
							progress.Description = devOne.Description;
							progress.FileName = file.Name;
							progress.BatchCount = batches.Count;
							progress.ProgressCaptionText = devOne.Development;
							progress.ProgressCountText = devUka.ToString() + "/" + devCnt.ToString();
							WorkingThread.DoProgress(progress);

							try
							{
								progress = new ScriptProgressData();
								foreach (string batch in batches)
								{	// Jednotlivé odstavce (oddělené GO):
									// Execute Scripts:
									using (Noris.Schedule.Support.Sql.TransactionWrapper tran = connector.CreateTransaction())
									{
										Noris.Schedule.Support.Sql.Db_Layer.ExecuteNonQuery(batch, 3600, connector);
										tran.Commit();
									}
								}
							}
							catch (Exception exc)
							{
								// Analýza chyby:
							}
						}
					}
				}
			}
		}
	}
	internal class ScriptorData
	{
		internal List<ConnectProfile> Profiles { get; set; }
		internal DevelopmentData Development { get; set; }
	}
	internal class ScriptProgressData : ProgressData
	{
		internal string Development { get; set; }
		internal string Description { get; set; }
		internal string FileName { get; set; }
		internal int BatchCount { get; set; }
	}
}
